package com.xbn.xbnmall.product.suanfa.completableFuture;

        import java.util.concurrent.CompletableFuture;
        import java.util.concurrent.ExecutionException;
        import java.util.concurrent.ExecutorService;
        import java.util.concurrent.Executors;

/**
 * @author XBN
 * @date 2020/8/9 15:29
 * @email 78742541@qq.com
 */
public class CompletableFutureDemo {
    public static ExecutorService executor= Executors.newFixedThreadPool(10);
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main函数开始");
        //第一个任务
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(
                () -> {
                    System.out.println("任务（1）查询用户信息:" + Thread.currentThread().getId());
                    int result = 1 + 1;
                    System.out.println("张三");
                    return "张三";
                }
                , executor);;

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(
                () -> {
                    System.out.println("任务（2）查询商品信息:" + Thread.currentThread().getId());

                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("衣服");
                    return "衣服";
                }
                , executor);
        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(
                () -> {
                    System.out.println("任务（3）查询当前地区信息:" + Thread.currentThread().getId());

                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("杭州");
                    return "杭州";
                }
                , executor);
        //任务4要在前面都运行完了再运行
        CompletableFuture<Object> objectCompletableFuture = CompletableFuture.anyOf(future1, future2, future3);
        Object o = objectCompletableFuture.get();//进行阻塞等待所有结果完成
        System.out.println("其中一个任务完成了，结果是:"+o.toString());

        System.out.println("main函数结束");
    }
}
